package com.qin.controller;

import java.io.IOException;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.qin.entity.Book;
import com.qin.entity.BookCategory;
import com.qin.entity.Press;
import com.qin.service.BookCategoryService;
import com.qin.service.BookService;
import com.qin.service.impl.BookCategoryServiceImpl;
import com.qin.service.impl.BookServiceImpl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.db.Db;
import cn.hutool.db.Entity;
import cn.hutool.db.handler.BeanHandler;
import cn.hutool.json.JSONUtil;

/**
 * 处理发的ajax请求，拿到price或press后author的信息
 */
@WebServlet("/getPriceOrPressOrAuthor")
public class GetPriceOrPressOrAuthorServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	private BookService bookService = new BookServiceImpl();
	private BookCategoryService bookCategoryService = new BookCategoryServiceImpl();
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String categoryId = request.getParameter("categoryId");
		String reqId = request.getParameter("reqId");
		
		// 先查询这个分类
		BookCategory bookCategoryById = bookCategoryService.getBookCategoryById(Long.parseLong(categoryId));
		
		Integer catLevel = bookCategoryById.getCatLevel();
		Long id = bookCategoryById.getId();
		
		List<Book> bookTarget = null;
		if(catLevel == 2) {
			// 查询当前分类id的所有图书
			bookTarget = bookService.getBooksByCategoryLevel2Id(id);
		}else if(catLevel == 3) {
			bookTarget = bookService.getBooksByCategoryLevel3Id(id);
		}
		
		switch(Integer.parseInt(reqId)) {
		case 2:
			// 拿到作者
			Set<String> collect = bookTarget.stream().flatMap(book->{
				String author = book.getAuthor();
				String trim = StrUtil.trim(author);
				String[] split = trim.split(";");
				return Arrays.asList(split).stream();
			}).collect(Collectors.toSet());
			
			// 转成JSON
			String jsonStr = JSONUtil.toJsonStr(collect);
			response.getWriter().print(jsonStr);
			break;
		case 3:
			// 拿到出版社
			Set<String> collect2 = bookTarget.stream().map(book->{
				Long pressId = book.getPressId();
				Press find = null;
				try {
					find = Db.use().find(Entity.create("press").set("id", pressId), new BeanHandler<Press>(Press.class));
				} catch (SQLException e) {
					e.printStackTrace();
				}
				return find.getName();
			}).collect(Collectors.toSet());
			
			// 转成JSON
			String jsonStr1 = JSONUtil.toJsonStr(collect2);
			response.getWriter().print(jsonStr1);
			break;
		}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
